import 'package:flutter_common_fragement/common/utils/index.dart';
import 'package:flutter_common_fragement/generated/json/base/json_convert_content.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

import '../../config/index.dart';
import '../index.dart';

abstract class BaseListViewModel<M, T> extends BaseViewModel {
  /// 分页页码
  int _page = 1;

  int get page => _page;

  /// 分页条目数量
  int _pageSize = 10;

  int get pageSize => _pageSize;

  void setPageSize(int pageSize) {
    _pageSize = pageSize;
    notifyListeners();
  }

  /// 刷新的控制器
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  /// 向外暴露的controller
  RefreshController get refreshController => _refreshController;

  /// list数据
  final List<T> _list = [];

  /// 向外暴露的list
  List<T> get list => _list;

  /// 设置请求的config配置
  late RequestConfig _requestConfig;

  void setRequestConfigParams({required Map<String, dynamic> otherParams}) {
    if (_requestConfig.method.toUpperCase() == 'GET') {
      final Map<String, dynamic> queryParameters =
          (_requestConfig.queryParameters ?? {});
      _requestConfig.queryParameters = queryParameters..addAll(otherParams);
    }
    if (_requestConfig.method.toUpperCase() == 'POST') {
      final Map<String, dynamic> data = _requestConfig.data ?? {};
      _requestConfig.data = data..addAll(otherParams);
    }

    _list.clear();
    notifyListeners();
    _page = 1;

    /// 重新加载数据
    onLoading();
  }

  void _setSearchParamsForRequestConfig() {
    if (_requestConfig.method.toUpperCase() == 'GET') {
      final Map<String, dynamic> queryParameters =
          (_requestConfig.queryParameters ?? {});
      _requestConfig.queryParameters = queryParameters
        ..addAll({
          'pageNo': _page,
          'pageSize': _pageSize,
        });
    }
    if (_requestConfig.method.toUpperCase() == 'POST') {
      final Map<String, dynamic> data = _requestConfig.data ?? {};
      _requestConfig.data = data
        ..addAll({
          'pageNo': _page,
          'pageSize': _pageSize,
        });
    }
  }

  // RequestConfig get requestConfig => setRequestConfig();

  /// 初始化 ---- viewModel 对应state 初始化的操作
  @override
  void initData() async {
    /// 初始化RequestConfig
    _requestConfig = initRequestConfig();

    /// 检查网络状态
    if (await checkNet()) {
      setNoNet(message: "没有网络");
      notifyListeners();
      return;
    }

    /// 保证list 是 空状态
    _list.clear();
    List<T> tempList = await getList();
    if (tempList.isEmpty) {
      setEmpty();
    } else {
      _list.addAll(tempList);
      setSuccess();
      onCompleted(_list);
    }
    notifyListeners();
  }

  /// 加载操作
  void onLoading() async {
    List<T> tempList = await getList();
    if (tempList.isEmpty) {
      _refreshController.loadNoData();
    } else {
      _list.addAll(tempList);
      _refreshController.loadComplete();
    }
    onCompleted(_list);
    notifyListeners();
  }

  /// 刷新操作
  void onRefresh() async {
    _list.clear();
    _page = 1;
    List<T> tempList = await getList();
    if (tempList.isEmpty) {
      setEmpty();
    } else {
      _list.addAll(tempList);
      setSuccess();
    }
    _refreshController.refreshCompleted(resetFooterState: true);
    onCompleted(_list);
    notifyListeners();
  }

  /// 获取list数据
  Future<List<T>> getList() async {
    try {
      final M model = await loadData();
      final List<T> tempList = formatResponseList(model);
      return tempList;
    } catch (e) {
      Log.e(e);
      rethrow;
    }
  }

  /// 获取数据 并且把返回的数据转换成model
  Future<M> loadData() async {
    /// 每次请求前 把 pageNo 跟 pageSize 挂上
    _setSearchParamsForRequestConfig();

    /// 获取数据
    final json = await sendRequest(_requestConfig);
    final M? model = JsonConvert.fromJsonAsT<M>(json.data);
    if (model == null) {
      setOther("数据转换错误");

      /// 转换数据 错误～ 基本可以自查
      throw TransformDataException();
    }

    /// 成功之后页面 +1
    _page++;

    return model;
  }

  /// 请求完成并且 数据已经给provider之后的操作
  void onCompleted(List<T> list) {}

  /// 初始化request config
  RequestConfig initRequestConfig();

  /// 格式化list数据 即 从model 到list的取值
  List<T> formatResponseList(M model);

  @override
  void viewModelDispose() {
    super.viewModelDispose();
    _refreshController.dispose();
  }
}
